<template>
  <div class="app-container">
    <el-dialog :title="id ? '修改' : '新增'" :visible.sync="visible" width="800px" :before-close="handleClose"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" />
        </el-form-item>
        <el-form-item label="模型类型" prop="preferTypes">
          <el-select v-model="form.preferTypes" placeholder="请选择模型类型" multiple ref="itemSelect" @change="handleChange">
            <el-option v-for="item in positionType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型图片" prop="imageUrl" v-if="visible">
          <FileUpload v-model="form.imageUrl" :fileType="['png', 'jpg', 'jpeg']" :url="url" @input="getFirelist"
            @deleteFile="deleteFile" @giveMediaType="giveMediaType" @getImageDimensions="getImageDimensions"
            ref="fileUpload" :limit="1" :drag="true" :listType="'picture'" :who="'imageUrl'"></FileUpload>
        </el-form-item>
        <el-form-item label="模型模体" prop="modelUrl" v-if="visible">
          <FileUpload v-model="form.modelUrl" :fileType="['glb']" :url="url" @input="getFirelist"
            @deleteFile="deleteFile" @giveMediaType="giveMediaType" ref="fileUpload2" :limit="1" :drag="true"
            :listType="'text'" :who="'modelUrl'"></FileUpload>
        </el-form-item>
        <el-col :span="12">
          <el-form-item label="模型长度" prop="w">
            <el-input v-model="form.w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模型宽度" prop="h">
            <el-input v-model="form.h" />
          </el-form-item>
        </el-col>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload/index2.vue";
import editorCom from "@/components/Editor";
import { addModel, editModel } from "@/api/model";
import { positiveNumberRules, specialRules } from "@/utils/rules";
import { getEnums } from "@/api/public";
export default {
  name: "Add",
  components: {
    FileUpload,
    editorCom,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    objTarget: {
      type: String,
      default: "",
    },
  },
  data() {
    const validatew = (rule, value, callback) => {
      if (!value) {
        callback(new Error("模型长度不能为空"));
      } else if (!positiveNumberRules.test(value)) {
        callback(new Error("模型长度只能为数字"));
      } else {
        callback();
      }
    };
    const validateh = (rule, value, callback) => {
      if (!value) {
        callback(new Error("模型宽度不能为空"));
      } else if (!positiveNumberRules.test(value)) {
        callback(new Error("模型宽度只能为数字"));
      } else {
        callback();
      }
    };
    return {
      form: {
        preferTypes: [],
      },
      rules: {
        modelName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" },
        ],
        preferTypes: [
          { required: true, message: "请选择模型类型", trigger: "change" },
        ],
        imageUrl: [
          { required: true, message: "请选择模型图片", trigger: "change" },
        ],
        modelUrl: [
          { required: true, message: "请选择模型模体", trigger: "change" },
        ],
        w: [{ required: true, validator: validatew, trigger: "blur" }],
        h: [{ required: true, validator: validateh, trigger: "blur" }],
      },
      url: "",
      imageOidList: [],
      modelOidList: [],
      positionType: [],
      originalW: 0,
      originalH: 0,
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail();
        }
      },
      deep: false,
      immediate: true,
    },
    visible: {
      handler(val) {
        if (val) {
          this.requestEnums();
        }
      },
      deep: false,
      immediate: true,
    },
  },
  methods: {
    requestEnums() {
      this.positionType = [];
      getEnums()
        .then((res) => {
          const obj = res?.data?.PositionType ?? {};
          if (Object.keys(obj).length > 0) {
            for (const key in obj) {
              this.positionType.push({
                label: obj[key],
                value: key,
              });
            }
          }
        })
        .catch((err) => { });
    },
    handleChange(val) {
      console.log(this.form);
    },
    handleInput(val) {
      this.form.description = val;
    },
    giveDetail() {
      let objTarget = JSON.parse(this.objTarget);
      // console.log(objTarget);
      this.form = {
        modelName: objTarget.modelName,
        imageUrl: [objTarget.imageUrl],
        modelUrl: [objTarget.modelUrl],
        preferTypes: objTarget.preferTypes ?? [],
        w: Number(objTarget.w),
        h: Number(objTarget.h),
        x: Number(objTarget.x),
        y: Number(objTarget.y),
        // z: Number(objTarget.z),
      };
      this.imageOidList = [objTarget.imageOid];
      this.modelOidList = [objTarget.modelOid];
    },
    getImageDimensions({ width, height }) {
      // 在这里处理图片宽高信息
      // console.log("图片宽高:", width, height);
      this.$set(this.form, "w", width);
      this.$set(this.form, "h", height);
      this.originalW = width;
      this.originalH = height;
    },
    giveMediaType(mediaType, who, applyTarget) {
      let obj = {
        path: "extend-model",
        mediaType: mediaType,
      };
      // suffix: who === "imageUrl" ? "jpg" : "glb",
      if (who === "imageUrl") {
        obj.suffix = mediaType.match(/\/(.+)/)[1];
      } else {
        obj.suffix = 'glb'
      }
      // obj.suffix = mediaType.match(/\/(.+)/)[1]
      let refName = who === "imageUrl" ? "fileUpload" : "fileUpload2";
      this.$refs[refName].loadUploadParams(obj);
    },
    getFirelist(data, who) {
      let arr;
      if (who === "imageUrl") {
        arr = this.imageOidList;
      } else {
        arr = this.modelOidList;
      }
      console.log(this.form, "123123");
      data.forEach((item) => {
        // imageOidList不包含该ossId则push
        if (item.ossId && !arr.includes(item.ossId)) {
          arr.push(item.ossId);
        }
      });
      this.$refs.fileUpload.resetDynamic();
    },
    deleteFile(file, who) {
      let flage, arr;
      if (who === "imageUrl") {
        flage = this.form.imageUrl;
        arr = this.imageOidList;
      } else {
        flage = this.form.modelUrl;
        arr = this.modelOidList;
      }
      let index = flage.findIndex((item) => {
        if (typeof item === "object" && Object.keys(item).length > 0) {
          return item.url === file.url;
        } else {
          return item === file.url;
        }
      });
      if (index !== -1) {
        // 找到imageOidList中对应的对象，删除
        flage.splice(index, 1);
        arr.splice(index, 1);
        if (who === "imageUrl") {
          this.$set(this.form, "w", 0);
          this.$set(this.form, "h", 0);
        }
      }
    },
    cancle() {
      this.handleClose(false);
    },
    sub() {
      // 触发表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg;
          let queryParams = {
            modelName: this.form.modelName,
            imageOid: this.imageOidList[0],
            modelOid: this.modelOidList[0],
            preferTypes: this.form.preferTypes,
            w: this.form.w,
            h: this.form.h,
            x: this.originalH ?? this.form.h,
            y: this.originalW ?? this.form.w,
            // z: this.form.z ?? 0.1,
          };
          if (this.id) {
            requestWay = editModel;
            queryParams.modelId = this.id;
            msg = "修改成功";
            errmsg = "修改失败";
          } else {
            requestWay = addModel;
            msg = "新增成功";
            errmsg = "新增失败";
          }
          console.log("提交表单数据:", queryParams);
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg);
                this.handleClose(true);
              } else {
                this.$message.error(errmsg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("表单校验未通过");
          return false;
        }
      });
    },
    handleClose(status) {
      this.form = {
        preferTypes: [],
      };
      this.imageOidList = [];
      this.modelOidList = [];
      // 重置表单
      this.$refs.form.resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style lang="scss" scoped></style>
